package fragmentson;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.wq.cycling.DemoHelper;
import com.wq.cycling.R;

import java.util.Timer;
import java.util.TimerTask;

import activity.ParentActivity;
import bean.MessageForSimple;
import fragmentson.backhandle.BackHandledFragment;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import service.ApiUtil;

/**
 * 注册
 * author：wangqi on 2017/4/26 17:48
 * email：773630555@qq.com
 */
public class LogonFragment_B extends BackHandledFragment {

	private View rootView;
	private String code="";
	private EditText et_code,et_phone,et_passwordone,et_passwordtwo;
	private TextView tv_getcode;
	private int a = 120;
	private Timer timer;
	private boolean canClick=false;
	/**
	 * reg 注册  resetpassword 重置密码
	 */
	private String module="reg";
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = getLayoutInflater(savedInstanceState).inflate(R.layout.fragment_logon_b, null);
		code = getArguments().getString("code");
		initView();
		return rootView;
	}

	private void initView() {
		// TODO Auto-generated method stub
		if(code.equals("1")) {
			((TextView) rootView.findViewById(R.id.tv_title)).setText(R.string.logon_register_title);
		}else{
			((TextView) rootView.findViewById(R.id.tv_title)).setText(R.string.logon_password_title);
		}
		rootView.findViewById(R.id.tv_next).setOnClickListener(listener);
		tv_getcode = ((TextView) rootView.findViewById(R.id.tv_getcode));
		tv_getcode.setOnClickListener(listener);
		et_passwordone = ((EditText) rootView.findViewById(R.id.et_passwordone));
		et_passwordtwo = ((EditText) rootView.findViewById(R.id.et_passwordtwo));
		et_code = ((EditText) rootView.findViewById(R.id.et_code));
        et_phone = ((EditText) rootView.findViewById(R.id.et_phone));
        et_phone.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
										  int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				if(s.toString().length()==11){
					canClick = true;
					tv_getcode.setBackgroundResource(R.drawable.corner_view_unline_green);
				}else{
					canClick = false;
					tv_getcode.setBackgroundResource(R.drawable.corner_view_unline_green_light);
				}
			}
		});
	}

	/**
	 *
	 * @param code 1来自注册 2来自忘记密码
	 * @return
	 */
	public static LogonFragment_B newInstance(String code) {
		LogonFragment_B fragment = new LogonFragment_B();
		Bundle bundle = new Bundle();
		bundle.putString("code",code);
		fragment.setArguments(bundle);
		return fragment;
	}

	private View.OnClickListener listener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()){
				case R.id.tv_next:
					if(!et_passwordone.getText().toString().equals(et_passwordtwo.getText().toString())){
						Toast.makeText(getActivity(),getResources().getString(R.string.error_password),Toast.LENGTH_LONG).show();
						return ;
					}
					if(code.equals("1")) {
						ApiUtil.getApiService().logon(et_phone.getText().toString(),et_code.getText().toString(),et_passwordone.getText().toString()).enqueue(new Callback<MessageForSimple>() {
							@Override
							public void onResponse(Call<MessageForSimple> call, Response<MessageForSimple> response) {
								try {
									MessageForSimple entity = response.body();
									if(entity.getCode().equals("10006")){
										new Thread(){
											public void run(){
												try {
													EMClient.getInstance().createAccount(et_phone.getText().toString(), et_passwordone.getText().toString());
													DemoHelper.getInstance().setCurrentUserName(et_phone.getText().toString());
													Log.d("logonhuanxin","注册成功");
												} catch (HyphenateException e) {
													e.printStackTrace();
													Log.d("logonhuanxin","注册失败");
												}
											}
										}.start();
										startActivity(new Intent(getActivity(), ParentActivity.class));
										getActivity().finish();
									}else{
										Toast.makeText(getActivity(),entity.getMsg(),Toast.LENGTH_LONG).show();
									}
								} catch (Exception e) {
									e.printStackTrace();
								}
							}

							@Override
							public void onFailure(Call<MessageForSimple> call, Throwable t) {
								Toast.makeText(getActivity(),getResources().getString(R.string.error),Toast.LENGTH_LONG).show();
							}
						});

					}else{
						ApiUtil.getApiService().forgotPassWord(et_phone.getText().toString(),et_code.getText().toString(),et_passwordone.getText().toString()).enqueue(new Callback<MessageForSimple>() {
							@Override
							public void onResponse(Call<MessageForSimple> call, Response<MessageForSimple> response) {
								try {
									MessageForSimple entity = response.body();
									if(entity.getCode().equals("10008")){
										startActivity(new Intent(getActivity(), ParentActivity.class));
										getActivity().finish();
									}else{
										Toast.makeText(getActivity(),entity.getMsg(),Toast.LENGTH_LONG).show();
									}
								} catch (Exception e) {
									e.printStackTrace();
								}
							}

							@Override
							public void onFailure(Call<MessageForSimple> call, Throwable t) {
								Toast.makeText(getActivity(),getResources().getString(R.string.error),Toast.LENGTH_LONG).show();
							}
						});
					}

					break;
				case R.id.tv_getcode:
					if (tv_getcode.getText().equals("发送验证码")&&canClick) {
						if(code.equals("1")) {
							module = "reg";
						}else{
							module = "resetpassword";
						}
						ApiUtil.getApiService().generateSMSCode(et_phone.getText().toString(),module).enqueue(new Callback<MessageForSimple>() {
							@Override
							public void onResponse(Call<MessageForSimple> call, Response<MessageForSimple> response) {
								try {
									MessageForSimple entity = response.body();
									if(entity.getCode().equals("10008")){
										tv_getcode.setBackgroundResource(R.drawable.corner_view_unline_green_light);
										et_phone.setEnabled(false);
										timing();
									}else{
										Toast.makeText(getActivity(),entity.getMsg(),Toast.LENGTH_LONG).show();
									}
								} catch (Exception e) {
									e.printStackTrace();
								}

							}
							@Override
							public void onFailure(Call<MessageForSimple> call, Throwable t) {
								Toast.makeText(getActivity(),getResources().getString(R.string.error),Toast.LENGTH_LONG).show();
							}
						});
					}
					break;
				default:
					break;
			}
		}
	};

	public void timing() {
		timer = new Timer(true);
		TimerTask task = new TimerTask() {
			public void run() {
				a--;
				if (a <= 0) {
					timer.cancel();
				}
				Message message = new Message();
				message.what = a;
				handler.sendMessage(message);
			}
		};
		timer.schedule(task, 0, 1000); // 延时1000ms后执行，1000ms执行一次
	}

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if(msg.what==0){
                et_phone.setEnabled(true);
				tv_getcode.setText("发送验证码");
				tv_getcode.setBackgroundResource(R.drawable.corner_view_unline_green);
				a=120;
			}else{
				tv_getcode.setText("剩余" + msg.what + "秒");
			}
			super.handleMessage(msg);
		}
	};

	@Override
	public boolean onBackPressed() {
		return false;
	}
	
}
